<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="./../reset.css"/>
    <link rel="stylesheet" href="./../common.css"/>
</head>
<body>
<h2>输入框的验证</h2>
<form class="review-form-1">
    用户名：<input type="text" name="username"/><br>
    密码：<input type="password" name="password"/><br>
    手机号：<input type="password" name="phone"/>
</form>

<p class="btns-line">
    <span class="btn-common-1 submit-form-1">提交</span>
</p>

<script>
    (function() {
        var strategies = {
            isNonEmpty: function(val, errorMsg) {
                if (val === '') {
                    return errorMsg
                }
            },

            minLength: function(val, length, errorMsg) {
                if (val.length < length) {
                    return errorMsg
                }
            },

            isMobile: function(val, errorMsg) {
                if (!/(^1[3|5|6|8|9][0-9]{9}$)/.test(val)) {
                    return errorMsg
                }
            }
        }

        var Validator = function() {
            this.cache = [];
        }

        Validator.prototype.add = function(dom, rule, errorMsg) {
            var ary = rule.split(':');
            this.cache.push(function() {
                var strategy = ary.shift();
                ary.unshift(dom.value);
                ary.push(errorMsg);
                return strategies[strategy].apply(dom, ary);
            })
        }

        Validator.prototype.start = function() {
            for (var i = 0, validatorFn; validatorFn = this.cache[i++];) {
                var errorMsg = validatorFn();
                if (errorMsg) {
                    return errorMsg;
                }
            }
        }

        var submitBtn = document.querySelector('.submit-form-1');

        submitBtn.onclick = function() {
            var form = document.querySelector('.review-form-1');
            var validator = new Validator();
            validator.add(form.username, 'isNonEmpty', '用户名不能为空');
            validator.add(form.password, 'minLength:6', '密码不能小于6位');
            validator.add(form.phone, 'isMobile', '手机号不合法');
            var result = validator.start();
            console.log(result);
        }
    })()
</script>
</body>
</html>